import axios from "axios"
import {Toast} from 'vant'
import {userStore} from '@/store/user';
import {useRoute, useRouter} from 'vue-router';
import {getToken} from "@/utils/auth";

let baseURL = "/api"
const service = axios.create({
    baseURL,
    timeout: 10000
})
const TOKEN_PREFIX = "Bearer "
// 发起请求之前的拦截器
service.interceptors.request.use(
    config => {
        let token = getToken() || ""
        if (token) {
            config.headers = {
                'Authorization': TOKEN_PREFIX + token
            }
        }
        return config
    },
    error => Promise.reject(error)
)
// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code == 401) {
            //认证失败跳转到登录页面
            Toast(res.msg)
            userStore().logout();
            useRouter().push('/login')
            return Promise.reject(new Error(res.msg))
        } else if (res.code == 500) {
            Toast(res.msg)
            return Promise.reject(new Error(res.msg))
        } else if (res.code != 200) {
            Toast(res.msg)
            return Promise.reject(new Error(res.msg))
        } else {
            return Promise.resolve(res)
        }
    },
    error => {
        return Promise.reject(error)
    }
)
export default service
